#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
工具函数模块

该模块提供各种工具函数，用于辅助测试执行。
"""

import json
import os
import re
from typing import Dict, List, Any, Optional, Union


def replace_variables(content: Any, variables: Dict[str, Any]) -> Any:
    """
    替换内容中的变量引用
    
    Args:
        content: 要处理的内容
        variables: 变量字典
        
    Returns:
        处理后的内容
    """
    if isinstance(content, dict):
        return {k: replace_variables(v, variables) for k, v in content.items()}
    elif isinstance(content, list):
        return [replace_variables(item, variables) for item in content]
    elif isinstance(content, str):
        # 替换${var}格式的变量
        pattern = r'\${([\w\.\-]+)}'
        matches = re.findall(pattern, content)
        
        result = content
        for var_name in matches:
            if var_name in variables:
                placeholder = f'${{{var_name}}}'
                value = variables[var_name]
                if isinstance(value, (dict, list)):
                    # 如果整个字符串就是一个变量引用，直接返回变量值
                    if content == placeholder:
                        return value
                    # 否则将复杂类型转换为字符串
                    value = json.dumps(value)
                result = result.replace(placeholder, str(value))
                
        return result
    else:
        return content


def merge_dicts(dict1: Dict[str, Any], dict2: Dict[str, Any]) -> Dict[str, Any]:
    """
    合并两个字典，dict2的值会覆盖dict1中的同名键
    
    Args:
        dict1: 第一个字典
        dict2: 第二个字典
        
    Returns:
        合并后的字典
    """
    result = dict1.copy()
    for key, value in dict2.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = merge_dicts(result[key], value)
        else:
            result[key] = value
    return result


def parse_jsonpath(data: Any, jsonpath: str) -> Optional[Any]:
    """
    简单的JSONPath解析函数
    
    Args:
        data: 要解析的数据
        jsonpath: JSONPath表达式
        
    Returns:
        解析结果，如果未找到则返回None
    """
    if not jsonpath.startswith('$'):
        return None
        
    # 移除开头的$
    path = jsonpath[1:]
    
    # 处理空路径
    if not path:
        return data
        
    # 分割路径
    segments = []
    current = ''
    in_brackets = False
    
    for char in path:
        if char == '.' and not in_brackets:
            if current:
                segments.append(current)
                current = ''
        elif char == '[' and not in_brackets:
            if current:
                segments.append(current)
                current = ''
            in_brackets = True
        elif char == ']' and in_brackets:
            in_brackets = False
        else:
            current += char
            
    if current:
        segments.append(current)
    
    # 遍历路径
    result = data
    for segment in segments:
        if not segment:
            continue
            
        if isinstance(result, dict):
            result = result.get(segment)
        elif isinstance(result, list) and segment.isdigit():
            index = int(segment)
            if 0 <= index < len(result):
                result = result[index]
            else:
                return None
        else:
            return None
            
        if result is None:
            return None
            
    return result


def format_request_params(params: Dict[str, Any]) -> str:
    """
    格式化请求参数为可读字符串
    
    Args:
        params: 请求参数字典
        
    Returns:
        格式化后的字符串
    """
    lines = []
    
    # URL和方法
    lines.append(f"URL: {params.get('url', 'N/A')}")
    lines.append(f"Method: {params.get('method', 'GET')}")
    
    # 请求头
    headers = params.get('headers', {})
    if headers:
        lines.append("\nHeaders:")
        for name, value in headers.items():
            lines.append(f"  {name}: {value}")
    
    # 查询参数
    query_params = params.get('params', {})
    if query_params:
        lines.append("\nQuery Parameters:")
        for name, value in query_params.items():
            lines.append(f"  {name}: {value}")
    
    # 请求体
    body = None
    if 'json' in params and params['json'] is not None:
        body = params['json']
        body_type = 'JSON'
    elif 'data' in params and params['data'] is not None:
        body = params['data']
        body_type = 'Form Data'
    
    if body is not None:
        lines.append(f"\n{body_type}:")
        if isinstance(body, dict):
            for name, value in body.items():
                if isinstance(value, (dict, list)):
                    value = json.dumps(value, ensure_ascii=False)
                lines.append(f"  {name}: {value}")
        else:
            lines.append(f"  {body}")
    
    # 文件
    files = params.get('files', {})
    if files:
        lines.append("\nFiles:")
        for name, file_obj in files.items():
            if hasattr(file_obj, 'name'):
                lines.append(f"  {name}: {file_obj.name}")
            else:
                lines.append(f"  {name}: <file>")
    
    return '\n'.join(lines)